package com.lanou.myapp.news.recommendednews;


import android.os.Handler;
import android.os.Message;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.lanou.myapp.R;
import com.lanou.myapp.imageloader.GsonRequest;
import com.lanou.myapp.imageloader.VolleySingleton;
import com.lanou.myapp.mode.DayNightMode;
import com.lanou.myapp.news.recommendednews.contentrecommendednews.ContentPictureNewsActivity;
import com.lanou.myapp.news.recommendednews.contentrecommendednews.ContentRecommendedNewsActivity;
import com.lanou.myapp.help.RankingComicDaoHelper;
import com.lanou.myapp.progressdialog.Dialog;
import com.lanou.myapp.refresh.PullToRefreshLayout;

import java.util.List;

/**
 * Created by dllo on 16/1/10.
 */
public class RecommendedNewsFragment extends Fragment {


    private String url = "http://interfacev5.vivame.cn/x1-interface-v5/json/newdatalist.json?platform=android&installversion=5.6.9.4&channelno=WDJTA2320480100&mid=5284047f4ffb4e04824a2fd1d1f0cd62&uid=3125&sid=ddeb07ea-e109-409d-80cf-8f9feee89196&type=1&id=9001&category=1&ot=0&nt=99987070";
    private Context context;
    private ListView listView;
    private RequestQueue queue;
    private ListNewsAdapter adapter;
    private List<RecommendedNews.DataEntity.FeedlistEntity> data;
    private RankingComicDaoHelper helper;
    private Dialog dialog;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        listView = (ListView) getActivity().findViewById(R.id.listView_recommended_news);
        adapter = new ListNewsAdapter(getActivity());
        dialog = new Dialog(context, "");
        dialog.setTitle("正在加载，请稍后...");
        dialog.show();

        GsonRequest<RecommendedNews> request = new GsonRequest<RecommendedNews>(url, RecommendedNews.class, new Response.Listener<RecommendedNews>() {
            @Override
            public void onResponse(final RecommendedNews response) {
                adapter.addData(response.getData().getFeedlist());
//                Log.d("dfaddsfds", response.getData().getFeedlist().size() + "");
                listView.setAdapter(adapter);
                dialog.dismiss();
                ((PullToRefreshLayout) getActivity().findViewById(R.id.refresh_view))
                        .setOnRefreshListener(new MyListener());

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (response.getData().getFeedlist().get(position).getItems().get(0).getStypename().equals("图集")) {
                            Intent intent = new Intent(getActivity(), ContentPictureNewsActivity.class);
                            intent.putExtra("Key", response.getData().getFeedlist().get(position).getItems().get(0).getUrl());
                            getActivity().startActivity(intent);
                        } else {
                            Intent intent = new Intent(getActivity(), ContentRecommendedNewsActivity.class);
                            intent.putExtra("key", response.getData().getFeedlist().get(position).getItems().get(0).getFileurl());
                            getActivity().startActivity(intent);
                        }
                    }
                });


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        VolleySingleton.getInstance()._addRequest(request);
//        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//                data = new ArrayList<>();
//                Gson gson = new Gson();
////                Type type = new TypeToken<List<Items>>(){}.getType();
////                data = gson.fromJson(response, type);
//                RecommendedNews beans = gson.fromJson(response, RecommendedNews.class);
//                data = beans.getData().getFeedlist();
//
//                adapter.addData(data);
//                listView.setAdapter(adapter);
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//
//            }
//        });
//        queue.add(request);
    }


    public class MyListener implements PullToRefreshLayout.OnRefreshListener {

        @Override
        public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
            // 下拉刷新操作
            new Handler() {
                @Override
                public void handleMessage(Message msg) {




                    GsonRequest<RecommendedNews> request = new GsonRequest<RecommendedNews>(url, RecommendedNews.class, new Response.Listener<RecommendedNews>() {
                        @Override
                        public void onResponse(final RecommendedNews response) {
                            adapter.addData(response.getData().getFeedlist());
                            listView.setAdapter(adapter);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    VolleySingleton.getInstance()._addRequest(request);

                    // 千万别忘了告诉控件刷新完毕了哦！
                    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                }
            }.sendEmptyMessageDelayed(0, 1000);
        }

        @Override
        public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {

            // 加载操作
            new Handler() {
                @Override
                public void handleMessage(Message msg) {



                    GsonRequest<RecommendedNews> request = new GsonRequest<RecommendedNews>(url, RecommendedNews.class, new Response.Listener<RecommendedNews>() {
                        @Override
                        public void onResponse(final RecommendedNews response) {
                            adapter.addData(response.getData().getFeedlist());
                            listView.setAdapter(adapter);
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    VolleySingleton.getInstance()._addRequest(request);


                    // 千万别忘了告诉控件加载完毕了哦！
                    pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
            }.sendEmptyMessageDelayed(0, 1000);
        }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_recommended_news, null);
        return view;
    }
}
